<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2019 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\service\airquality\AirQualityService;
use app\common\service\FlugGasService;
use think\Db;
use think\facade\Config;

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

/**
 * 空气质量预报-首页
 */
class AirQuality extends BaseController
{
    // +----------------------------------------------------------------------
    // | 目录
    // | 2.1 获取7天的空气质量趋势图 getAirQualityTrend
    // | 2.2 获取7天的首要污染物 primaryPollution
    // +----------------------------------------------------------------------
    
    /**
     * 2.1 获取7天的空气质量趋势图
     * @author JiYun On 2019/03/01
     */
    public function getAirQualityTrend()
    {
        $param = $this->request->param();

        $list = [];

        try {
            $airQualityService = new AirQualityService();
            $list              = $airQualityService->getAirQualityTrend($param);

            if (empty($list)) {
                $this->error('获取7天的空气质量趋势数据失败!');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('获取7天的空气质量趋势数据成功!', $list);
    }

    /**
     * 2.2 获取7天的首要污染物
     * @author JiYun On 2019/03/04
     */
    public function primaryPollution()
    {
        $param = $this->request->param();

        $list = [];

        try {
            $airQualityService = new AirQualityService();
            $list              = $airQualityService->primaryPollution($param);

            if (empty($list)) {
                $this->error('获取首要污染物数据失败！');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('获取首要污染物数据成功！', $list);
    }

    /**
     * 2.0-1空气质量趋势图
     * zhugeng 2019-03-25
     */
    public function airQualityForecast()
    {
        $param = $this->request->param();
        //判断参数
        if (!isset($param['station_id']) || !isset($param['pollutant'])) {
            return $this->error('参数不存在！');
        }

        $param['pollutant'] = strtolower($param['pollutant']);
        $param['pollutant'] = str_replace('.','',$param['pollutant']);
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //未来7天（包括今天）
            $afterDate = self::get_after_weeks();
            $param['start_date'] = $afterDate[0];
            $param['end_date'] = $afterDate[6];
        } else {
            $afterDate = self::getDateFromRange($param['start_date'],$param['end_date']);
        }
        $data['date'] = $afterDate;
        //预报值
//        if (strtotime($param['end_date']) > strtotime(date('Y-m-d',time()))) {
//            //预报值
//            $sqlForecast = "select ".$param['pollutant'].",aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
//            $forecastResult = Db::query($sqlForecast,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date'],date('Y-m-d',time())));
//        } else {
//            //预报值
//            $sqlForecast = "select ".$param['pollutant'].",aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and predict_time = publish_time";
//            $forecastResult = Db::query($sqlForecast,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date']));
//        }
        if (strtolower($param['pollutant']) == 'o3') {
            $field = 'o3,o3_8hour,o3_iaqi,o3_8h_iaqi';
            $field_realtime = 'o3,o3_8hour,o3_iaqi,o3_8hour_iaqi as o3_8h_iaqi';
        } else {
            $field = $param['pollutant'];
            $field_realtime = $param['pollutant'];
        }
        //预报值
        if (strtotime($param['end_date']) > strtotime(date('Y-m-d',time()))) {
            $sqlForecast    = 'select '.$field.',aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and is_integer = 1 and predict_time between ? and ? and publish_time = ?';
            $forecastResult = Db::query($sqlForecast, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00',date('Y-m-d',time())));
        } else {
            $sqlForecast    = 'select '.$field.',aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and is_integer = 1 and predict_time between ? and ? and publish_time = predict_time';
            $forecastResult = Db::query($sqlForecast, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', $param['end_date'].' 23:00:00'));
        }
        //实际值
        $sqlpractical = 'select '.$field_realtime.',aqi,publish_time as pt_time from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list = Db::query($sqlpractical,array($param['region_id'],$param['station_id'],$param['start_date'].' 00:00:00',$param['end_date'].' 23:00:00'));
        if (count($forecastResult) <= 0) {
            foreach ($afterDate as $k => $v) {
                $data['data'][0][$k] = '';
            }
        } else {
            //数据处理
            $newList = [];
            $newDate = [];
            foreach ($forecastResult as $k => $v) {
                if (strtolower($param['pollutant']) == 'o3') {
                    if ($v['o3_iaqi'] >= $v['o3_8h_iaqi']) {
                        $pollutant = 'o3';
                    } else {
                        $pollutant = 'o3_8hour';
                    }
                    $v[$pollutant] = round($v[$pollutant]);
                } elseif (strtolower($param['pollutant']) == 'co') {
                    $pollutant = 'co';
                    $v[$pollutant] = round($v[$pollutant],1);
                } elseif (strtolower($param['pollutant']) == 'aqi') {
                    $pollutant = 'aqi';
                    $v[$pollutant] = ceil($v[$pollutant]);
                } else {
                    $pollutant = $param['pollutant'];
                    $v[$pollutant] = round($v[$pollutant]);
                }
//                if ($param['pollutant'] == 'CO' || $param['pollutant'] == 'co') {
//                    $v[$param['pollutant']] = round($v[$param['pollutant']],1);
//                } else {
//                    $v[$param['pollutant']] = round($v[$param['pollutant']]);
//                }
                $newList[date('m/d',strtotime($v['pt_time']))][] = $v[$pollutant];
                array_push($newDate,date('m/d',strtotime($v['pt_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            //预报
            foreach ($afterDate as $k => $v) {
                if (in_array($v,$newDate)) {
                    $data['data'][0][$k] = $newList[$v][0];
                } else {
                    $data['data'][0][$k] = '';
                }
            }
        }
        if (count($list) <= 0) {
            foreach ($afterDate as $k => $v) {
                $data['data'][1][$k] = '';
            }
        } else {
            //数据处理
            $newList1 = [];
            $newDate1 = [];
            foreach ($list as $k => $v) {
                if ($param['pollutant'] == 'CO' || $param['pollutant'] == 'co') {
                    $pollutant = 'co';
                    $v[$pollutant] = round($v[$pollutant],1);
                } elseif (strtolower($param['pollutant']) == 'o3') {
                    if ($v['o3_iaqi'] >= $v['o3_8h_iaqi']) {
                        $pollutant = 'o3';
                        $v[$pollutant] = round($v['o3']);
                    } else {
                        $pollutant = 'o3_8hour';
                        $v[$pollutant] = round($v['o3_8hour']);
                    }
                } elseif (strtolower($param['pollutant']) == 'aqi') {
                    $pollutant = 'aqi';
                    $v[$pollutant] = ceil($v[$pollutant]);
                } else {
                    $pollutant = $param['pollutant'];
                    $v[$pollutant] = round($v[$pollutant]);
                }
                $newList1[date('m/d',strtotime($v['pt_time']))][] = $v[$pollutant];
                array_push($newDate1,date('m/d',strtotime($v['pt_time'])));
            }
            $newDate1 = array_values(array_unique($newDate1));//去重，重新排列索引
            //实际
            foreach ($afterDate as $k => $v) {
                if (in_array($v,$newDate1)) {
                    $data['data'][1][$k] = $newList1[$v][0];
                } else {
                    $data['data'][1][$k] = '';
                }
            }
        }
        $this->success('成功',$data);
    }

    /**
     * 2.0-2首要污染物
     * zhugeng 2019-03-26
     */
    public function chiePollutant()
    {
        $param = $this->request->param();
        //判断参数
        if (!isset($param['region_id']) || !isset($param['station_id']) || !isset($param['start_date']) || !isset($param['end_date'])) {
            return $this->error('参数不存在！');
        }
        if (empty($param['region_id'])) {
            return $this->error('参数错误！');
        }
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //未来7天（包括今天）
            $afterDate = self::get_after_weeks();
            $param['start_date'] = $afterDate[0];
            $param['end_date'] = $afterDate[6];
        } else {
            $afterDate = self::getDateFromRange($param['start_date'],$param['end_date']);
        }
        $data['date'] = $afterDate;
        if (strtotime($param['end_date']) > strtotime(date('Y-m-d',time()))) {
            //预报值
            $sqlForecast = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
            $forecastResult = Db::query($sqlForecast,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date'],date('Y-m-d',time())));
        } else {
            //预报
            $sql_forecast_over1 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = predict_time";
            $forecastResult1 = Db::query($sql_forecast_over1, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', date("Y-m-d 00:00:00", strtotime("-1 day"))));
            //预报
            $sql_forecast_over2 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = ?";
            $forecastResult2 = Db::query($sql_forecast_over2, array($param['region_id'], $param['station_id'], date('Y-m-d 00:00:00',time()), $param['end_date'].' 00:00:00',date('Y-m-d 00:00:00',time())));
            $forecastResult = array_merge_recursive($forecastResult1,$forecastResult2);

//            //预报值
//            $sqlForecast = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and predict_time = publish_time";
//            $forecastResult = Db::query($sqlForecast,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date']));
        }
        if (count($forecastResult) <= 0) {
            foreach ($afterDate as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => '', 'type' => 1];
            }
        } else {
            //数据处理
            $newList2 = [];
            foreach ($forecastResult as $k => $v) {
                if (date('H',strtotime($v['dt_time'])) == '12') {
                    array_splice($forecastResult,$k,1);//删除数组元素，索引重组
                } else {
                    $newList2[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }
            }
//            $newList2 = [
//                '06/01'=>[
//                    0=>['name'=>'O3','value'=>100],
//                    1=>['name'=>'O3_8H','value'=>105],
//                    2=>['name'=>'CO','value'=>101],
//                ],
//                '06/02'=>[
//                    0=>['name'=>'O3','value'=>100],
//                    1=>['name'=>'CO','value'=>101],
//                    2=>['name'=>'O3_8H','value'=>105],
//                ]
//            ];
            //处理O3和O3_8H
            foreach ($newList2 as $k1 => $v1) {
                for ($i=0;$i<count($v1);$i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList2 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            if (max($temp) > 1) {
                for ($j = 0; $j < max($temp); $j++) {
                    for ($k = 0; $k < count($afterDate); $k++) {
                        if (!isset($newList2[$afterDate[$k]][$j]['name'])) {
                            $data['data'][$j][] = ['name' => '', 'value' => '', 'type' => 1];
                        } else {
                            if (strtoupper($newList2[$afterDate[$k]][$j]['name']) == 'O3_8H') {
                                $newList2[$afterDate[$k]][$j]['name'] = 'O3';
                            }
                            $data['data'][$j][] = ['name' => strtoupper($newList2[$afterDate[$k]][$j]['name']), 'value' => $newList2[$afterDate[$k]][$j]['value'], 'type' => 1];
                        }
                    }
                }
            } else {
                for ($j = 0; $j < max($temp); $j++) {
                    for ($k = 0; $k < count($afterDate); $k++) {
                        if (!isset($newList2[$afterDate[$k]][$j]['name'])) {
                            $data['data'][0][] = ['name' => '', 'value' => '', 'type' => 1];
                        } else {
                            if (strtoupper($newList2[$afterDate[$k]][$j]['name']) == 'O3_8H') {
                                $newList2[$afterDate[$k]][$j]['name'] = 'O3';
                            }
                            $data['data'][0][] = ['name' => strtoupper($newList2[$afterDate[$k]][$j]['name']), 'value' => $newList2[$afterDate[$k]][$j]['value'], 'type' => 1];
                        }
                    }
                }
            }

        }

        //实际值
        $sqlpractical = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list         = Db::query($sqlpractical, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        if (count($list) <= 0) {
            foreach ($afterDate as $k => $v) {
                $data['data'][1][] = ['name' => '', 'value' => '', 'type' => 2];
            }
        } else {
            //数据处理
//            $newList1 = [];
//            foreach ($list as $k => $v) {
//                $newList1[date('m/d',strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
//            }
            //实际
            $newList3 = [];
            foreach ($list as $k => $v) {
                $newList3[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
            }
            //处理O3和O3_8H
            foreach ($newList3 as $k1 => $v1) {
                for ($i=0;$i<count($v1);$i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList3[$k1],$i,1);//删除数组元素，索引重组
                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList3 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num = count($data['data']);
            if (max($temp) > 1) {
                for ($j = 0; $j < max($temp); $j++) {
                    for ($k = 0; $k < count($afterDate); $k++) {
                        if (!isset($newList3[$afterDate[$k]][$j]['name'])) {
                            $data['data'][$j+$num][] = ['name' => '', 'value' => '', 'type' => 2];
                        } else {
                            if (strtoupper($newList3[$afterDate[$k]][$j]['name']) == 'O3_8H') {
                                $newList3[$afterDate[$k]][$j]['name'] = 'O3';
                            }
                            $data['data'][$j+$num][] = ['name' => strtoupper($newList3[$afterDate[$k]][$j]['name']), 'value' => $newList3[$afterDate[$k]][$j]['value'], 'type' => 2];
                        }
                    }
                }
            } else {
                for ($j = 0; $j < max($temp); $j++) {
                    for ($k = 0; $k < count($afterDate); $k++) {
                        if (!isset($newList3[$afterDate[$k]][$j]['name'])) {
                            $data['data'][$j+$num][] = ['name' => '', 'value' => '', 'type' => 2];
                        } else {
                            if (strtoupper($newList3[$afterDate[$k]][$j]['name']) == 'O3_8H') {
                                $newList3[$afterDate[$k]][$j]['name'] = 'O3';
                            }
                            $data['data'][$j+$num][] = ['name' => strtoupper($newList3[$afterDate[$k]][$j]['name']), 'value' => $newList3[$afterDate[$k]][$j]['value'], 'type' => 2];
                        }
                    }
                }
            }
        }
        $this->success('成功',$data);
    }


    /**
     *2.0-3 相关污染物
     * zhugeng 2019-03-28
     */
    public function correlationPollutant()
    {
        $param = $this->request->param();
        //判断参数
        if (empty(trim($param['region_id'])) || empty(trim($param['start_date'])) || empty(trim($param['end_date']))) {
            return $this->error('参数无效！');
        }
        if (empty(trim($param['start_date'])) && empty(trim($param['end_date']))) {
            //未来7天（包括今天）
            $lastYearWeek = self::get_after_weeks(time()+86400);
            $param['start_date'] = $lastYearWeek[0];
            $param['end_date'] = $lastYearWeek[6];
        } else {
            $lastYearWeek = self::getDateFromRange($param['start_date'],$param['end_date']);
        }
        //未来7天（不包括今天）
        $data['date'] = $lastYearWeek;
        //选择全市显示超标污染物，选择站点显示相关污染物
        if ($param['station_id'] != 0) {
            //相关污染物
            if (strtotime($param['end_date']) < strtotime(date('Y-m-d',time()))) {
                //实际值(上周或者过去时间段)
                $sql_history = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $list = Db::query($sql_history,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date']));
            } else {
                //计算今天到结束日期相差天数
                $days = $this->diffBetweenTwoDays($param['start_date'],date('Y-m-d',time()))+1;
                if ($days > 1) {
                    //实际+预报（本周或者今天日期在所选日期范围内）
                    //实际
                    $sql_week = "select name,value,publish_time as pt_time from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                    $weekList = Db::query($sql_week,array($param['region_id'],$param['station_id'],$param['start_date'],date("Y-m-d",strtotime("-1 day"))));
                    //预报
                    $sql_forecast = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                    $forecastList = Db::query($sql_forecast,array($param['region_id'],$param['station_id'],date("Y-m-d",time()),$param['end_date'],date("Y-m-d",time())));
                    if (count($weekList) > 0 && count($forecastList) > 0) {
                        $list = array_merge($weekList,$forecastList);
                    } else {
                        if (count($weekList) > 0) {
                            $list = $weekList;
                        }
                        if (count($forecastList) > 0) {
                            $list = $forecastList;
                        }
                    }
                } else {
                    //预报（未来日期范围，包括今天）
                    $sql = "select name,value,predict_time as pt_time from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                    $list = Db::query($sql,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date'],date("Y-m-d",time())));
                }
            }
            if (count($list) <= 0) {
                foreach ($lastYearWeek as $k => $v) {
                    $data['data'][0][] = ['name'=>'','value'=>'','type'=>1];
                }
            } else {
                $newList = [];
                $newDate = [];
                for ($i = 0;$i < count($list); $i++) {
                    $newList[date("Y-m-d",strtotime($list[$i]['pt_time']))][] = $list[$i];
                    array_push($newDate,date('m/d',strtotime($list[$i]['pt_time'])));
                }
                $newDate = array_values(array_unique($newDate));//去重，重新排列索引
                //处理O3和O3_8H
                foreach ($newList as $k1 => $v1) {
                    for ($i=0;$i<count($v1);$i++) {
                        foreach ($v1 as $k2 => $v2) {
                            if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                                array_splice($newList[$k1],$i,1);//删除数组元素，索引重组
                            }
                        }
                    }
                }
                //根据首要污染物查询相关污染物
                $correlation = [];
                foreach ($newList as $k => $v) {
                    if (strtotime($k) >= strtotime(date('Y-m-d',time()))) {
                        foreach ($v as $k1 => $v1) {
                            //查询相关污染物预报表
                            $sql_forecast1 = "select primary_name,primary_value,relevance_name,relevance_value,publish_time as dt_time from air_quality_station_relevance_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ? and pearson_value >= 0.75 and primary_name = ?";
                            $forecastList1 = Db::query($sql_forecast1,array($param['region_id'],$param['station_id'],$k,date("Y-m-d 00:00:00",time()),$v1['name']));
                            if (count($forecastList1) > 0) {
                                foreach ($forecastList1 as $k2 => $v2) {
                                    if ($v1['name'] == $v2['relevance_name']) {
                                        array_splice($forecastList1, $k2, 1);//删除数组元素，索引重组
                                    }
                                    if ($v1['name'] == 'O3' && $v2['relevance_name'] == 'O3' || $v2['relevance_name'] == 'O3_8H') {
                                        array_splice($forecastList1, $k2, 1);//删除数组元素，索引重组
                                    }
                                    if ($v1['name'] == 'O3_8H' && $v2['relevance_name'] == 'O3' || $v2['relevance_name'] == 'O3_8H') {
                                        array_splice($forecastList1, $k2, 1);//删除数组元素，索引重组
                                    }
                                }
                                $correlation[$k] = $forecastList1;
                            }
                        }

                    } else {
                        foreach ($v as $k1 => $v1) {
                            //查询相关污染物实际表
                            $sql_history1 = "select primary_name,primary_value,relevance_name,relevance_value,publish_time as dt_time from air_quality_station_relevance_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time = ? and pearson_value >= 0.75 and primary_name = ?";
                            $pollutantResult = Db::query($sql_history1,array($param['region_id'],$param['station_id'],$k,$v1['name']));
                            if (count($pollutantResult) > 0) {
                                foreach ($pollutantResult as $k2 => $v2) {
                                    if ($v1['name'] == $v2['relevance_name']) {
                                        array_splice($pollutantResult, $k2, 1);//删除数组元素，索引重组
                                    }
                                    if ($v1['name'] == 'O3' && $v2['relevance_name'] == 'O3' || $v2['relevance_name'] == 'O3_8H') {
                                        array_splice($forecastList1, $k2, 1);//删除数组元素，索引重组
                                    }
                                    if ($v1['name'] == 'O3_8H' && $v2['relevance_name'] == 'O3' || $v2['relevance_name'] == 'O3_8H') {
                                        array_splice($forecastList1, $k2, 1);//删除数组元素，索引重组
                                    }
                                }
                                $correlation[$k] = $pollutantResult;
                            }
                        }
                    }
                }

                //根据相关污染物查询六参浓度值
                $concentrationList = [];
                foreach ($correlation as $k => $v) {
                    if (strtotime($k) >= strtotime(date('Y-m-d',time()))) {
                        if (!empty($v)) {
                            foreach ($v as $k1 => $v1) {
                                if ($v1['relevance_name'] == 'PM2_5' || $v1['relevance_name'] == 'PM2.5') {
                                    $v1['relevance_name'] = 'pm25';
                                }
                                //查询浓度值预报表
                                $sql_con = 'select '.strtolower($v1['relevance_name']).' from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time = ? and publish_time = ?';
                                $concentration = Db::query($sql_con,array($param['region_id'],$param['station_id'],$k,date('Y-m-d',time())));
                                if (count($concentration) > 0) {
                                    if ($v1['relevance_name'] == 'CO' || $v1['relevance_name'] == 'co') {
                                        $concentration[0][strtolower($v1['relevance_name'])] = round($concentration[0][strtolower($v1['relevance_name'])],1);
                                    } else {
                                        $concentration[0][strtolower($v1['relevance_name'])] = round($concentration[0][strtolower($v1['relevance_name'])]);
                                    }
                                    $concentrationList[date('m/d',strtotime($k))][] = ['name'=>strtoupper($v1['relevance_name']),'value'=>$concentration[0][strtolower($v1['relevance_name'])]];
                                }
                            }
                        }

                    } else {
                        if (!empty($v)) {
                            foreach ($v as $k1 => $v1) {
                                //查询浓度值实际表
                                if ($v1['relevance_name'] == 'PM2.5' || $v1['relevance_name'] == 'pm2.5') {
                                    $v1['relevance_name'] = 'pm25';
                                }
                                $sql_forecast1 = 'select '.strtolower($v1['relevance_name']).' from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time = ?';
                                $concentration = Db::query($sql_forecast1,array($param['region_id'],$param['station_id'],$k));
                                if (count($concentration) > 0) {
                                    if ($v1['relevance_name'] == 'CO' || $v1['relevance_name'] == 'co') {
                                        $concentration[0][strtolower($v1['relevance_name'])] = round($concentration[0][strtolower($v1['relevance_name'])],1);
                                    } else {
                                        $concentration[0][strtolower($v1['relevance_name'])] = round($concentration[0][strtolower($v1['relevance_name'])]);
                                    }
                                    $concentrationList[date('m/d',strtotime($k))][] = ['name'=>$v1['relevance_name'],'value'=>$concentration[0][strtolower($v1['relevance_name'])]];
                                }
                            }
                        }
                    }
                }
                //整合数据
                if (count($concentrationList) > 0) {
                    foreach ($concentrationList as $k1 => $v1) {
                        //处理O3和O3_8H
                        for ($i=0;$i<count($v1);$i++) {
                            foreach ($v1 as $k2 => $v2) {
                                if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                                    array_splice($concentrationList[$k1],$i,1);//删除数组元素，索引重组
                                }
                            }
                        }
                    }

                    $temp = [];
                    foreach ($concentrationList as $k1 => $v1) {
                        $temp[$k1] = count($v1);
                    }
                    for ($i=0;$i<max($temp);$i++) {
                        foreach ($lastYearWeek as $k => $v) {
                            if (in_array($v,$newDate)) {
                                if (isset($concentrationList[$v][$i])) {
                                    if (strtoupper($concentrationList[$v][$i]['name']) == 'O3_8H') {
                                        $newList3[$concentrationList[$v]][$i]['name'] = 'O3';
                                    }
                                    if (strtoupper($concentrationList[$v][$i]['name']) == 'PM25') {
                                        $concentrationList[$v][$i]['name'] = 'PM2.5';
                                    }
                                    $concentrationList[$v][$i]['name'] = strtoupper($concentrationList[$v][$i]['name']);
                                    $data['data'][$i][] = $concentrationList[$v][$i];
                                } else {
                                    $data['data'][$i][] = ['name'=>'','value'=>''];
                                }
                            } else {
                                $data['data'][$i][] = ['name'=>'','value'=>''];
                            }
                        }
                    }
                } else {
                    $data['data'] = [];
                }

            }
        } else {
            //超标污染物
            if (strtotime($param['end_date']) <= strtotime(date('Y-m-d',time()))) {
                //实际值(上周或者过去时间段)
                $sql_history_over = "select name,value,publish_time as pt_time from air_quality_station_non_attainment_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                $list = Db::query($sql_history_over,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date']));
            } else {
                //计算今天到结束日期相差天数
                $days = $this->diffBetweenTwoDays($param['start_date'],date('Y-m-d',time()))+1;
                if ($days > 1) {
                    //实际+预报（本周或者今天日期在所选日期范围内）
                    //实际
                    $sql_week_over = "select name,value,publish_time as pt_time from air_quality_station_non_attainment_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?";
                    $weekList = Db::query($sql_week_over,array($param['region_id'],$param['station_id'],$param['start_date'],date("Y-m-d",strtotime("-1 day"))));
                    //预报
                    $sql_forecast_over = "select name,value,predict_time as pt_time from air_quality_station_non_attainment_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                    $forecastList = Db::query($sql_forecast_over,array($param['region_id'],$param['station_id'],date("Y-m-d",time()),$param['end_date'],date("Y-m-d",time())));
                    if (count($weekList) > 0 && count($forecastList) > 0) {
                        $list = array_merge($weekList,$forecastList);
                    } else {
                        if (count($weekList) > 0) {
                            $list = $weekList;
                        }
                        if (count($forecastList) > 0) {
                            $list = $forecastList;
                        }
                    }
                } else {
                    //预报（未来日期范围，包括今天）
                    $sql = "select name,value,predict_time as pt_time from air_quality_station_non_attainment_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?";
                    $list = Db::query($sql,array($param['region_id'],$param['station_id'],$param['start_date'],$param['end_date'],date("Y-m-d",time())));
                }
            }
            if (count($list) <= 0) {
                foreach ($lastYearWeek as $k => $v) {
                    $data['data'][0][] = ['name'=>'','value'=>''];
                }
            } else {
                $newList = [];
                $newDate = [];
                for ($i = 0;$i < count($list); $i++) {
                    $newList[date("m/d",strtotime($list[$i]['pt_time']))][] = $list[$i];
                    array_push($newDate,date('m/d',strtotime($list[$i]['pt_time'])));
                }
                $newDate = array_values(array_unique($newDate));//去重，重新排列索引
                foreach ($newList as $k1 => $v1) {
                    //处理O3和O3_8H
                    for ($i=0;$i<count($v1);$i++) {
                        foreach ($v1 as $k2 => $v2) {
                            if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                                array_splice($newList[$k1],$i,1);//删除数组元素，索引重组
                            }
                        }
                    }

                }
                $temp = [];
                foreach ($newList as $k1 => $v1) {
                    $temp[$k1] = count($v1);
                }
                for ($i=0;$i<max($temp);$i++) {
                    foreach ($lastYearWeek as $k => $v) {
                        if (in_array($v,$newDate)) {
                            if (isset($newList[$v][$i])) {
                                if (strtoupper($newList[$v][$i]['name']) == 'O3_8H') {
                                    $newList[$v][$i]['name'] = 'O3';
                                }
                                if (strtoupper($newList[$v][$i]['name']) == 'PM25') {
                                    $newList[$v][$i]['name'] = 'PM2.5';
                                }
                                $data['data'][$i][] = ['name'=>strtoupper($newList[$v][$i]['name']),'value'=>$newList[$v][$i]['value']];
                            } else {
                                $data['data'][$i][] = ['name'=>'','value'=>''];
                            }
                        } else {
                            $data['data'][$i][] = ['name'=>'','value'=>''];
                        }
                    }
                }
            }
        }
        $this->success('成功',$data);
    }
    /**
     * 2.0-4空气质量预报-贡献度（弃用）
     * zhugeng 2019-03-26
     */
    public function airContributionTrend()
    {
        $param = $this->request->param();
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        //本地
        //$this->PDOManager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
        $PDOBulk = new \MongoDB\Driver\BulkWrite;//插入
        $opt    = [
            'projection' => [],
        ];
        //判断参数
        if (!isset($param['station_id']) || !isset($param['industry_id'])) {
            return $this->error('参数不存在！');
        }
        if (empty(trim($param['industry_id']))) {
            return $this->error('参数无效！');
        }

        if (empty(trim($param['start_date'])) && empty(trim($param['end_date']))) {
            //未来7天（包括今天）
            $afterDate = self::get_after_weeks();
            $param['start_date'] = $afterDate[0];
            $param['end_date'] = $afterDate[6];
        } else {
            $afterDate = self::getDateFromRange($param['start_date'],$param['end_date']);
        }
        $data['date'] = $afterDate;
        //条件参数
        $map = [
            'region_id'               => (int)$param['region_id'],
            "station_id"              => (int)$param['station_id'],
            "industry_id"             => $param['industry_id'],
            "predict_time"            => ['$gte' => $param['start_date'],'$lte' => $param['end_date']],
            '$where'                  => 'this.publish_time = '.date('Y-m-d',time())
        ];
        // 1工业、2非工业
        if ($param['industry_id'] == 1) {
            $map['industry_id'] = ['$in'=>Config::get('industry_limit_arr_mongodb')];
        } else {
            $map['industry_id'] = ['$in'=>[8,9,10,11]];
        }

        $query  = new \MongoDB\Driver\Query($map, $opt);//查询
        $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_station_forecast_day', $query)->toArray();
        $list = json_decode(json_encode($cursor),true);
        if (count($list) <= 0) {
            foreach ($afterDate as $k => $v) {
                $data['data'][0][] = '';
                $data['data'][1][] = '';
                $data['data'][2][] = '';
            }
        } else {
            $newList = [];
            $newDate = [];
            for ($i = 0;$i < count($list); $i++) {
                $newList[date("m/d",strtotime($list[$i]['predict_time']))][] = ['name'=>$list[$i]['contribution_name'],'value'=>$list[$i]['contribution_value'],'type'=>1];
                array_push($newDate,date('m/d',strtotime($list[$i]['predict_time'])));
            }
            $newDate = array_values(array_unique($newDate));//去重，重新排列索引
            foreach ($afterDate as $k => $v) {
                foreach ($list as $k1 => $v1) {
                    if ($v == date('m/d',strtotime($v1['publish_time']))) {
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'PM2.5') {
                            $data['data'][0][] = $v1['contribution_value']*100;
                        }
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'SO2') {
                            $data['data'][1][] = $v1['contribution_value']*100;
                        }
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'NO2') {
                            $data['data'][2][] = $v1['contribution_value']*100;
                        }
                    }
                }
            }
        }
        $this->success('成功',$data);
    }

    /**
     * 获取今天之后（包含今天）七天所有日期
     */
    function get_after_weeks($time = '', $format='m/d'){
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i=0; $i<7; $i++){
            //-1包含今天
            $date[$i] = date($format ,strtotime( '+' . $i .'days', $time));
        }
        return $date;
    }
    /**
     * @author zhugeng 2019-05-07
     * @param $day1 开始日期
     * @param $day2 结束日期
     * @return float|int 相差天数
     */
    function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }
    /**
     * 获取指定日期段内每一天的日期
     * @param  Date  $startdate 开始日期
     * @param  Date  $enddate   结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate){
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;
        // 保存每天日期
        $date = array();
        for($i=0; $i<$days; $i++){
            $date[] = date('m/d', $stimestamp+(86400*$i));
        }
        return $date;
    }

}
